// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 加载统计数据
    loadStats();
    
    // 加载热门话题
    loadHotTopics(7); // 默认显示近7天
    
    // 加载最新资讯
    loadLatestNews();
    
    // 加载热门论文
    loadPopularPapers();
    
    // 加载企业动态
    loadCompanyActivity();
    
    // 绑定事件处理
    setupEventHandlers();
});

// 加载统计数据
function loadStats() {
    // 在实际应用中，这些数据应该从API获取
    // 这里使用模拟数据
    Promise.all([
        axios.get(`${API_BASE_URL}${API_ENDPOINTS.trends}?days=7&group_by=day`),
        axios.get(`${API_BASE_URL}${API_ENDPOINTS.popularPapers}?days=7&limit=5`),
        axios.get(`${API_BASE_URL}${API_ENDPOINTS.companyActivity}?days=7`)
    ])
    .then(responses => {
        const trendsData = responses[0].data.data;
        const papersData = responses[1].data.data;
        const companyData = responses[2].data.data;
        
        // 更新统计卡片
        updateStatsCards(trendsData, papersData, companyData);
    })
    .catch(error => {
        console.error('Error loading stats:', error);
        // 出错时显示默认值
        document.getElementById('todayUpdateCount').textContent = '0';
        document.getElementById('todayUpdateChange').textContent = '0%';
        document.getElementById('hotPapersCount').textContent = '0';
        document.getElementById('companyNewsCount').textContent = '0';
        document.getElementById('companyCount').textContent = '0';
        document.getElementById('hotTopicsCount').textContent = '0';
    });
}

// 更新统计卡片
function updateStatsCards(trendsData, papersData, companyData) {
    // 今日更新数
    const todayData = trendsData.time_series[trendsData.time_series.length - 1];
    const yesterdayData = trendsData.time_series[trendsData.time_series.length - 2];
    
    const todayCount = todayData ? todayData.total || 0 : 0;
    const yesterdayCount = yesterdayData ? yesterdayData.total || 0 : 0;
    
    // 计算变化百分比
    let changePercent = 0;
    if (yesterdayCount > 0) {
        changePercent = ((todayCount - yesterdayCount) / yesterdayCount * 100).toFixed(1);
    }
    
    // 更新今日更新卡片
    document.getElementById('todayUpdateCount').textContent = todayCount;
    const changeElement = document.getElementById('todayUpdateChange');
    changeElement.textContent = `${changePercent > 0 ? '+' : ''}${changePercent}%`;
    changeElement.className = changePercent >= 0 ? 'text-success' : 'text-danger';
    
    // 热门论文数量
    document.getElementById('hotPapersCount').textContent = papersData.length;
    
    // 企业动态
    const companyNewsCount = companyData.reduce((sum, company) => sum + company.count, 0);
    document.getElementById('companyNewsCount').textContent = companyNewsCount;
    document.getElementById('companyCount').textContent = companyData.length;
    
    // 热门话题数量
    const categoryCounts = trendsData.category_trends.length;
    document.getElementById('hotTopicsCount').textContent = categoryCounts;
}

// 加载热门话题
function loadHotTopics(days) {
    axios.get(`${API_BASE_URL}${API_ENDPOINTS.hotTopics}?days=${days}&limit=8`)
        .then(response => {
            const topics = response.data.data;
            renderHotTopics(topics);
        })
        .catch(error => {
            handleError(error);
            // 加载失败时显示错误提示
            document.getElementById('hotTopics').innerHTML = `
                <div class="col-12">
                    <div class="alert alert-warning">
                        加载热门话题失败，请稍后再试
                    </div>
                </div>
            `;
        });
}

// 渲染热门话题
function renderHotTopics(topics) {
    const container = document.getElementById('hotTopics');
    
    if (!topics || topics.length === 0) {
        container.innerHTML = '<div class="col-12"><div class="alert alert-info">暂无热门话题</div></div>';
        return;
    }
    
    let html = '';
    
    topics.forEach(topic => {
        const topItems = topic.top_items.slice(0, 3);
        const itemsHtml = topItems.map(item => {
            return `<li><a href="detail.html?id=${item._id || item.id}&type=${item.type}" class="text-decoration-none">${truncateText(item.title, 50)}</a></li>`;
        }).join('');
        
        html += `
            <div class="col-md-3 mb-3">
                <div class="card h-100">
                    <div class="card-body">
                        <h5 class="card-title">${topic.topic}</h5>
                        <p class="card-text">
                            <span class="badge bg-primary">${topic.count}篇相关内容</span>
                        </p>
                        <ul class="small ps-3">
                            ${itemsHtml}
                        </ul>
                    </div>
                    <div class="card-footer">
                        <a href="search.html?topic=${encodeURIComponent(topic.topic)}" class="btn btn-sm btn-outline-primary">查看全部</a>
                    </div>
                </div>
            </div>
        `;
    });
    
    container.innerHTML = html;
}

// 加载最新资讯
function loadLatestNews(page = 1, filter = 'all') {
    const pageSize = 5;
    let url = `${API_BASE_URL}${API_ENDPOINTS.news}?page=${page}&page_size=${pageSize}`;
    
    if (filter !== 'all') {
        url += `&type=${filter}`;
    }
    
    axios.get(url)
        .then(response => {
            const data = response.data.data;
            renderLatestNews(data.items, page === 1);
            
            // 更新"加载更多"按钮状态
            const loadMoreBtn = document.getElementById('loadMoreNews');
            if (page * pageSize >= data.pagination.total) {
                loadMoreBtn.disabled = true;
                loadMoreBtn.innerText = '没有更多了';
            } else {
                loadMoreBtn.disabled = false;
                loadMoreBtn.innerText = '加载更多';
                
                // 更新按钮的数据属性，用于加载下一页
                loadMoreBtn.dataset.page = page + 1;
                loadMoreBtn.dataset.filter = filter;
            }
        })
        .catch(error => {
            handleError(error);
            document.getElementById('latestNews').innerHTML = `
                <div class="alert alert-warning">
                    加载最新资讯失败，请稍后再试
                </div>
            `;
        });
}

// 渲染最新资讯
function renderLatestNews(news, isFirstPage) {
    const container = document.getElementById('latestNews');
    
    if (!news || news.length === 0) {
        if (isFirstPage) {
            container.innerHTML = '<div class="alert alert-info">暂无最新资讯</div>';
        }
        return;
    }
    
    let html = '';
    
    news.forEach(item => {
        const date = formatDate(item.published_date || item.created_at);
        const tags = generateTags(item.topic_categories || []);
        
        html += `
            <a href="detail.html?id=${item._id || item.id}&type=${item.type}" class="list-group-item list-group-item-action">
                <div class="d-flex w-100 justify-content-between">
                    <h5 class="mb-1">${item.title}</h5>
                    <small>${date}</small>
                </div>
                <p class="mb-1">${truncateText(item.summary || '', 150)}</p>
                <small>
                    ${tags}
                    <span class="badge bg-light text-dark">${item.source || '未知来源'}</span>
                </small>
            </a>
        `;
    });
    
    if (isFirstPage) {
        container.innerHTML = html;
    } else {
        container.insertAdjacentHTML('beforeend', html);
    }
}

// 加载热门论文
function loadPopularPapers() {
    axios.get(`${API_BASE_URL}${API_ENDPOINTS.popularPapers}?days=30&limit=5`)
        .then(response => {
            const papers = response.data.data;
            renderPopularPapers(papers);
        })
        .catch(error => {
            handleError(error);
            document.getElementById('popularPapers').innerHTML = `
                <div class="alert alert-warning">
                    加载热门论文失败，请稍后再试
                </div>
            `;
        });
}

// 渲染热门论文
function renderPopularPapers(papers) {
    const container = document.getElementById('popularPapers');
    
    if (!papers || papers.length === 0) {
        container.innerHTML = '<div class="alert alert-info">暂无热门论文</div>';
        return;
    }
    
    let html = '';
    
    papers.forEach(paper => {
        const date = formatDate(paper.published_date || paper.created_at);
        const citations = paper.citation_count ? `<span class="badge bg-success me-1">${paper.citation_count}引用</span>` : '';
        
        html += `
            <a href="detail.html?id=${paper._id || paper.id}&type=paper" class="list-group-item list-group-item-action">
                <div class="d-flex w-100 justify-content-between">
                    <h5 class="mb-1">${truncateText(paper.title, 70)}</h5>
                </div>
                <p class="mb-1 small text-muted">
                    ${truncateText(paper.authors ? paper.authors.join(', ') : '未知作者', 80)}
                </p>
                <small>
                    ${citations}
                    <span class="badge bg-light text-dark">${date}</span>
                </small>
            </a>
        `;
    });
    
    container.innerHTML = html;
}

// 加载企业动态
function loadCompanyActivity() {
    axios.get(`${API_BASE_URL}${API_ENDPOINTS.companyActivity}?days=30`)
        .then(response => {
            const companies = response.data.data;
            renderCompanyActivity(companies);
        })
        .catch(error => {
            handleError(error);
            document.getElementById('companyActivity').innerHTML = `
                <div class="col-12">
                    <div class="alert alert-warning">
                        加载企业动态失败，请稍后再试
                    </div>
                </div>
            `;
        });
}

// 渲染企业动态
function renderCompanyActivity(companies) {
    const container = document.getElementById('companyActivity');
    
    if (!companies || companies.length === 0) {
        container.innerHTML = '<div class="col-12"><div class="alert alert-info">暂无企业动态</div></div>';
        return;
    }
    
    // 只显示前8家企业
    const topCompanies = companies.slice(0, 8);
    let html = '';
    
    topCompanies.forEach(company => {
        const latestItem = company.items.length > 0 ? company.items[0] : null;
        const latestTitle = latestItem ? truncateText(latestItem.title, 60) : '暂无动态';
        const latestDate = latestItem ? formatDate(latestItem.published_date || latestItem.created_at) : '';
        
        html += `
            <div class="col-md-3 mb-3">
                <div class="card h-100">
                    <div class="card-body">
                        <h5 class="card-title">${company.company}</h5>
                        <p class="card-text">
                            <span class="badge bg-info">${company.count}篇最新动态</span>
                        </p>
                        <p class="small">${latestTitle}</p>
                    </div>
                    <div class="card-footer d-flex justify-content-between align-items-center">
                        <small class="text-muted">${latestDate}</small>
                        <a href="company-detail.html?name=${encodeURIComponent(company.company)}" class="btn btn-sm btn-outline-primary">详情</a>
                    </div>
                </div>
            </div>
        `;
    });
    
    container.innerHTML = html;
}

// 设置事件处理
function setupEventHandlers() {
    // 热门话题时间范围切换
    const topicPeriodButtons = document.querySelectorAll('[data-period]');
    topicPeriodButtons.forEach(button => {
        button.addEventListener('click', function() {
            // 移除所有按钮的active类
            topicPeriodButtons.forEach(btn => btn.classList.remove('active'));
            // 为当前按钮添加active类
            this.classList.add('active');
            
            // 加载对应时间范围的数据
            const days = parseInt(this.dataset.period);
            loadHotTopics(days);
        });
    });
    
    // 资讯筛选
    const newsFilterLinks = document.querySelectorAll('[data-filter]');
    newsFilterLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            // 移除所有筛选项的active类
            newsFilterLinks.forEach(l => l.classList.remove('active'));
            // 为当前筛选项添加active类
            this.classList.add('active');
            
            // 加载筛选后的数据
            const filter = this.dataset.filter;
            loadLatestNews(1, filter);
            
            // 更新下拉菜单按钮文本
            const dropdownButton = document.getElementById('newsFilterDropdown');
            if (dropdownButton) {
                dropdownButton.textContent = this.textContent;
            }
        });
    });
    
    // 加载更多新闻
    const loadMoreBtn = document.getElementById('loadMoreNews');
    if (loadMoreBtn) {
        loadMoreBtn.addEventListener('click', function() {
            const nextPage = parseInt(this.dataset.page || 2);
            const filter = this.dataset.filter || 'all';
            loadLatestNews(nextPage, filter);
        });
    }
} 